import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, Platform, ToastController} from 'ionic-angular';
import {Uid} from "@ionic-native/uid";
import {AndroidPermissions} from "@ionic-native/android-permissions";

import {ApiProvider} from "../../providers/api/api";
import {Hotspot} from "@ionic-native/hotspot";
import { Device } from '@ionic-native/device';
import {MainPage} from "../main/main";
import {Res} from "../../modal/Res";
import { LocalStorProvider } from '../../providers/local-stor/local-stor';
import {RegisterPage} from "../register/register";
import {ForgetPasswordPage} from "../forget-password/forget-password";

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  username="";
  password="";
/*  macaddr = '08-00-27-4A-19-EC';
  macIP= '192.168.0.125';*/
/*  clientType='Android';*/

  backFlag=false;//手机原生返回回退键标识

  constructor(public navCtrl: NavController, public navParams: NavParams, public uid: Uid, private androidPermissions: AndroidPermissions, public http: ApiProvider,private hotspot: Hotspot,
              private device:Device,private storage:LocalStorProvider,public platform:Platform,private toastCtrl: ToastController) {
/*    this.platform.registerBackButtonAction( () => {
      this.existApp();
    });*/
  }

  /**
   * 当页面加载的时候触发，仅在页面创建的时候触发一次，如果被缓存了，那么下次再打开这个页面则不会触发
   */
  ionViewDidLoad() {
    if(typeof(this.navParams.get("logName"))!='undefined')
    {
      this.username=this.navParams.get("logName");
      this.password="";
    }
    else
    {
      this.storage.getKey("logName").then(val=>{
        if(val!=null)
        {
          this.username=val;
        }
      });
    }

    //this.hotspot.getNetConfig().then(res=>{this.macIP=res.deviceIPAddress});

    //this.clientType=this.device.platform;

/*    const hasPermission = this.androidPermissions.checkPermission(
      this.androidPermissions.PERMISSION.READ_PHONE_STATE
    );

    if (!hasPermission) {
      const result = this.androidPermissions.requestPermission(
        this.androidPermissions.PERMISSION.READ_PHONE_STATE
      );

      if (!result['hasPermission']) {
        throw new Error('Permissions required');
      }

      return;
    }

    this.macaddr = this.uid.MAC;*/
  }

  /**
   * 当进入页面时触发
   */
  ionViewDidEnter()
  {
    if(typeof(this.navParams.get("logName"))!='undefined')
    {
      this.username=this.navParams.get("logName");
      this.password="";
    }
    else
    {
      this.storage.getKey("logName").then(val=>{
        if(val!=null)
        {
          this.username=val;
        }
      });
    }
/*    this.hotspot.getNetConfig().then(res=>{this.macIP=res.deviceIPAddress});

    this.clientType=this.device.platform;

    const hasPermission = this.androidPermissions.checkPermission(
      this.androidPermissions.PERMISSION.READ_PHONE_STATE
    );

    if (!hasPermission) {
      const result = this.androidPermissions.requestPermission(
        this.androidPermissions.PERMISSION.READ_PHONE_STATE
      );

      if (!result['hasPermission']) {
        throw new Error('Permissions required');
      }

      return;
    }

    this.macaddr = this.uid.MAC;*/
  }

  /**
   * 教师登录
   */
  login() {
    const params={logName:this.username,confirmPassword:this.password
/*      ,clientIp:this.macIP,clientType:'Android',macAddr:'08-00-27-4A-19-EC'*/
    };
    this.http.post("/loginTeacherController/userTeaLogin.do",params).subscribe( (item: Res) => {
      if(item.Code=="11111111")
        //this.http.errorAlert(item.Message);
        this.http.showToast(item.Message,"bottom");
      else
        {

          console.log(1);
          console.log(item);
          this.navCtrl.setRoot(MainPage);
          localStorage.setItem('teacherId',JSON.stringify(item.UserId));


          this.storage.setKey("user_id",item.UserId);
          this.storage.setKey("email",item.email);
          this.storage.setKey("studentid",item.studentid);
          this.storage.setKey("headpicture",item.headpicture);
          this.storage.setKey("logName",this.username);
          this.storage.setKey("real_name",item.real_name);


          this.navCtrl.push(MainPage);
        }
      },
      error => {
        console.log('POST call in error', error);
      },
      () => {
        //console.log('The POST observable is now completed.');
      }
    )
  }

/*  /!**
   * 学生注册
   *!/
  register()
  {
    this.navCtrl.push(RegisterPage);
  }

  /!**
   * 忘记密码
   *!/
  forgetPassword()
  {
    this.navCtrl.push(ForgetPasswordPage);
  }*/

  existApp()
  {
    if(!this.backFlag)
    {
      this.backFlag=true;
      let toast = this.toastCtrl.create({
        message: '再按一次退出程序',
        duration: 3000,
        position: 'bottom'
      });

      toast.onDidDismiss(() => {
        this.backFlag=false;
      });

      toast.present();
    }
    else
    {
      this.platform.exitApp();
    }
  }
}
